package com.msh.frame.client.validation;


import com.msh.frame.client.exception.ServiceException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EnumValidator implements ConstraintValidator<IValidateEnum, Object> {
    private IEnumValidate[] validates;

    @Override
    public void initialize(IValidateEnum validateEnum) {
        ConstraintValidator.super.initialize(validateEnum);
        Class<? extends IEnumValidate> classes = validateEnum.targetClass();
        if (!classes.isEnum()) {
            throw new ServiceException("系统错误: 错误的类型: " + classes.getName());
        }
        validates = classes.getEnumConstants();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        if(null == o){
            return true;
        }
        for (IEnumValidate e : validates) {
            if (e.validate(o)) {
                return true;
            }
        }
        return false;
    }
}
